package com.hr.fer.nmbp.lab2.test;

import java.io.Reader;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.hr.fer.nmbp.lab2.domain.Book;
import com.hr.fer.nmbp.lab2.persistence.BookMapper;

public class Main {
	
	
	private static SqlSession session = null;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
            System.out.println("Program started");
            String aResource = "myBatisConfig.xml";
            Reader reader = Resources.getResourceAsReader(aResource);
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
            System.out.println(sessionFactory.getConfiguration().getEnvironment().getDataSource().toString());
            session = sessionFactory.openSession();
            BookMapper mapper = session.getMapper(BookMapper.class);
            List<Book> books = mapper.selectAll();
            if(books.size() == 1) {
            	mapper.update(new Book(1, "2nd Lecture", "Randy Pausch", "2003"));
            }
            if (books.size() == 0) {
                Book b = new Book();
                b.setId(1);
                b.setAuthorName("Randy Pausch");
                b.setTitle("The last lecture");
                b.setYear("2003");
                System.out.println("Inserting: " + b.getTitle());
                mapper.insert(b);
            } else {
            	//mapper.delete(1);
            }
//            Contact jane = (Contact) session.selectOne("select", 2);
//            System.out.println(jane.getFirstName());
//            System.out.println().info("List<Contact> size=" + contacts.size());
//            System.out.println().info("List<Contact> content:");
//            for (Contact contact : contacts) {
//                System.out.println().info("Contact: " + contact);
//            }
//            mapper.delete(1);
//            contacts = mapper.selectAll();
//            for (Contact contact : contacts) {
//                System.out.println().info("Contact: " + contact);
//            }
            session.commit();
        } catch (Exception e) {
            System.err.println("Exception caught: " + e.getMessage());
        } finally {
            if (session != null) {
                session.close();
            }
        }
	}

}
